#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

void* thread1(void* argc){
  int count=0;
  while(1){
    printf("I am thread1\n");
    sleep(1);
    count++;
    if(count==5){
      printf("thread1 is return\n");
      return (void*)1;
    }
  }
}
void* thread2(void* argc){
  int count=0;
  while(1){
    sleep(1);
    count++;
    printf("I am thread2\n");
    if(count==5){
      printf("thread2 is exit\n");
      pthread_exit((void*) 2);
    }
  }
}
void* thread3(void* argc){
  while(1){
    sleep(1);
    printf("I am thread3\n");
  }
}

int main(){

  pthread_t tid1;
  pthread_t tid2;
  pthread_t tid3;

  pthread_create(&tid1,NULL,thread1,NULL);
  pthread_create(&tid2,NULL,thread2,NULL);
  pthread_create(&tid3,NULL,thread3,NULL);
  
  int count=0;
  while(1){
    count++;
    sleep(1);
    printf("I am main   thread\n");
    if(count==5){
      printf("thread3 is cancel\n");
      pthread_cancel(tid3);
      break;
    }
  }
  
//  pthread_detach(tid1);
//  pthread_detach(tid2);
//  pthread_detach(tid3);


  void* retval1;
  void* retval2;
  void* retval3;

  pthread_join(tid1,&retval1);
  pthread_join(tid2,&retval2);
  pthread_join(tid3,&retval3);

  printf("thread1 return code is: %d\n",(int)retval1);
  printf("thread2 exit   code is: %d\n",(int)retval2);
  printf("thread3 cancel code is: %d\n",(int)retval3);

  


  return 0;
}
